//
//  DataBaseManager.m
//  UI20_豆瓣电影storyBoard
//
//  Created by 王阳阳 on 16/1/7.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "DataBaseManager.h"

@implementation DataBaseManager

+ (DataBaseManager *)shareInstance
{
    static DataBaseManager *dbManager = nil;
    if (!dbManager) {
        dbManager = [[DataBaseManager alloc]init];
    }
    return dbManager;
}
//打开数据库
- (void)openDB
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"detai.db"];
    
    int result= sqlite3_open(path.UTF8String, &dbPoint);
    
    NSLog(@"打开数据库:%d, 路径:%@",result ,path);

}
//创建表格
- (void)createTable
{
    NSString *createSQL = @"create table if not exists detai (subject text , userid number)";
    //, movieId integer primary key autoincrement
    int result = sqlite3_exec(dbPoint, createSQL.UTF8String, NULL, NULL, NULL);

    [self jugdgeResulr:result message:@"创建表格"];
}

//增加
- (void)insertMovie:(DetailSecondModel *)m
{
    NSString *insertSQL = [NSString stringWithFormat:@"insert into detai(subject , userid) values('%@', '%@')", m.subject , m.user_id];
    int result = sqlite3_exec(dbPoint, insertSQL.UTF8String, NULL, NULL, NULL);
    NSLog(@"%@",m.user_id);

        [self jugdgeResulr:result message:@"增加数据"];

    
    
}

//查询
- (NSMutableArray *)selectMovie
{
    NSString *selectSQL = @"select * from detai";
    sqlite3_stmt *stmt = nil;
    int result = sqlite3_prepare_v2(dbPoint, selectSQL.UTF8String, -1, &stmt, nil);
    NSMutableArray *arr = [NSMutableArray array];
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {

            const unsigned char *mName = sqlite3_column_text(stmt, 0);
            DetailSecondModel *m = [[DetailSecondModel alloc]init];
            m.subject = [NSString stringWithUTF8String:(const char *)mName];

            [arr addObject:m];
        }
    }
    else
    {
        NSLog(@"失败:%d",result);
    }
    return arr;
}

- (void)deleteMovieWithName:(NSString *)movieName
{
    NSString *deleteSQL = [NSString stringWithFormat:@"delete from detai where subject = '%@'",movieName];
    //2.执行
    int result = sqlite3_exec(dbPoint, deleteSQL.UTF8String, NULL, NULL, NULL);
    //3.判断
    [self jugdgeResulr:result message:@"删除数据"];
}



- (void)jugdgeResulr:(int)r message:(NSString *)mes
{
    if (r == SQLITE_OK) {
        NSLog(@"%@成功",mes);
    }
    else
    {
        NSLog(@"%@失败:%d",mes,r);
    }
}

@end
